package com.onerway.common;

import com.onerway.exception.OnerWayConvertTreeMapException;

import java.lang.reflect.Field;
import java.util.TreeMap;

/**
 * 实例转treeMap的能力
 */
public interface TreeMapable {

    /**
     * 实体转treeMap
     *
     * @return
     */
    default TreeMap<String, Object> toTreeMap() {
        TreeMap<String, Object> treeMap = new TreeMap<>();
        Field[] fields = this.getClass().getDeclaredFields();

        for (Field field : fields) {
            try {
                // 设置为可访问私有字段
                field.setAccessible(true);
                // 获取字段值
                Object value = field.get(this);
                // 只添加非空值
                if (value != null) {
                    treeMap.put(field.getName(), value);
                }
            } catch (IllegalAccessException e) {
                throw new OnerWayConvertTreeMapException("Failed to get field value", e);
            }
        }
        return treeMap;
    }
}
